import { defineStore } from 'pinia';
import { ref, toRaw } from 'vue';
import TabStorage from '@/utils/tabstorage'
import { useRouter } from 'vue-router'



const useTabsStore = defineStore('tabs', () => {
    const router = useRouter()
    // tab列表
    const tabList = ref(TabStorage.getTab())
    // 活跃tab
    const tabActive = ref('/home')
    // 设置活跃tab
    const setTabActive = (path) => {

        tabActive.value = path
    }
    // 更新tab列表
    const updateTabsList = (tab) => {
        TabStorage.setTab(JSON.stringify([...toRaw(tabList.value), tab]))
        tabList.value = TabStorage.getTab()
    }
    // 删除指定tab
    const deleteTabs = (path) => {
        // 删除前所在位置
        const currentIndex = tabList.value.findIndex(item => item.path === path)
        // 删除
        TabStorage.setTab(JSON.stringify([...toRaw(tabList.value.filter(item => item.path !== path))]))
        // 获取
        tabList.value = TabStorage.getTab()
        // 删除的tab为活跃tab
        if (path === tabActive.value) {
            // 删除后还有多个tab
            if (tabList.value.length > 1) {
                // 删除tab所处位置为最后1个
                if (currentIndex === tabList.value.length) {
                    router.push({ path: tabList.value[currentIndex - 1].path })
                } else {
                    router.push({ path: tabList.value[currentIndex].path })
                }
            } else {
                router.push({ path: '/home' })
            }
        }


    }

    // 关闭全部 除了首页
    const shutAll = () => {
        TabStorage.setTab(JSON.stringify([...toRaw(tabList.value.filter(item => item.path === '/home'))]))
        tabList.value = TabStorage.getTab()
        router.push({ path: '/home' })

    }

    return { tabList, tabActive, updateTabsList, setTabActive, deleteTabs, shutAll }

})


export default useTabsStore